package com.imooc.mall.service.impl;

import com.imooc.mall.exception.ImoocMallException;
import com.imooc.mall.exception.ImoocMallExceptionEnum;
import com.imooc.mall.model.dao.UserMapper;
import com.imooc.mall.model.pojo.User;
import com.imooc.mall.service.UserService;
import com.imooc.mall.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;

/*
*  UserService 实现的类
* */
@Service("userService")
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Override
    public User getUser() {
        return userMapper.selectByPrimaryKey(1);
    }

    @Override
    public void register(String username, String password) throws ImoocMallException {
        // 先去判断是不是拥有这个类的同名的判断
        User result = userMapper.selectByName(username);
        if(result != null){
            //不应该在service层触碰到controller层业务代码相关的东西
            throw new ImoocMallException(ImoocMallExceptionEnum.NAME_EXISTED);
        }
        //写入数据库
        User user = new User();
        try {
            user.setPassword(MD5Utils.getMD5str(password));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        user.setUsername(username);
        int count = userMapper.insertSelective(user);
        if (count == 0 ){
            throw new ImoocMallException(ImoocMallExceptionEnum.INSERT_FAILED);
        }
    }

    @Override
    public User login(String username, String password) throws NoSuchAlgorithmException, ImoocMallException {
        String md5str = MD5Utils.getMD5str(password);
        User user = userMapper.selectByNamePassword(username, md5str);
        if(user == null){
            throw new ImoocMallException(ImoocMallExceptionEnum.WRONG_PASSWORD);
        }
        return user;
    }

    /**
     * 更新个性签名 前提是要先登录 判读是否登录先 再进行查找iD的值来判断更新的内容
     * @param SessionUser  登录的对象
     * @param signature  用户名
     * @throws ImoocMallException  更新异常的参数
     */
    @Transactional
    public void update(User SessionUser,String signature) throws ImoocMallException {
        User user = new User();
        user = userMapper.selectByPrimaryKey(SessionUser.getId());
        user.setPersonalizedSignature(signature);
        int updateCount = userMapper.updateByPrimaryKeySelective(user);
        // 这次只更新一个值
        if(updateCount > 1){
            throw new ImoocMallException(ImoocMallExceptionEnum.UPDATE_FAILED);
        }
    }
    @Override
     public boolean checkAdminRole(User user){
        return user.getRole().equals(2);
     }
}